import { http } from '../../utils/http'
import {populateFormData} from '../../utils/util'
import { encrypt } from '../../utils/util';
export default {
    login({ commit }, payload) {
        const params = populateFormData(payload.user);
        http.post( "/user/login", params).then((resp) => {
            if(resp.data.login==='yes'){
                let user={userName:payload.user.userName}
                user.key=Math.floor(Math.random()*1000000)
                user.userPass=encrypt(payload.user.userPass, user.key)
                if(payload.user.rem){
                    localStorage.setItem('user',JSON.stringify(user))
                }
                sessionStorage.setItem('user',JSON.stringify(resp.data.user));
                sessionStorage.setItem("logonUser",JSON.stringify(user));
                commit('login', resp.data.user);
                payload.success()
            }else{
                payload.fail()
            }
           
        })

    },
    logout({ commit }) {
        http.post( "/user/logout").
        then(resp=>{
            if(resp.data.logout==='yes'){
                localStorage.removeItem('user')
                sessionStorage.removeItem('user')
                sessionStorage.removeItem('logonUser')
                commit('logout')
            }
        })
    },
    fetchUserAddress({commit}){
        http.get("/address/getMyAddress").
        then(resp=>{
                commit('saveAddresses',resp.data.addrs)
        })
    },
    createOrUpdateAddress({commit},payload){
        const params = populateFormData(payload.address);
        http.post( "/address/handleAddress", params).then((resp) => {
            if(resp.data.code===0){
                if(!payload.address.addrId){
                    payload.address.addrId=resp.data.addrId;
                }
                commit('addOrUpdateAddress', payload.address);
                payload.success()
            }else{
                payload.fail()
            }
           
        })
    },
    removeAddress({commit},payload){
        const params=new URLSearchParams();
        params.append('addrId', payload.address.addrId)
        console.log(payload)
        http.post( "/address/delAddress", params).then((resp) => {
            if(resp.data.code===0){
                commit('removeAddressById', payload.address);
                payload.success()
            }else{
                payload.fail()
            }
           
        })
    },
    setDefaultAddress(context,payload){
        const params=new URLSearchParams();
        params.append('addrId', payload.address.addrId)
        console.log(payload)
        http.post( "/address/setDefaultAddress", params).then((resp) => {
            if(resp.data.code===0){
                payload.success()
            }else{
                payload.fail()
            }
           
        })
    }
}
